package com.recruit.server.service.impl;

import com.recruit.server.common.HeaderInfo;
import com.recruit.server.common.utils.BigDecimalUtil;
import com.recruit.server.dao.CartMapper;
import com.recruit.server.dao.ProductMapper;
import com.recruit.server.entity.pojo.Cart;
import com.recruit.server.entity.pojo.Product;
import com.recruit.server.request.cart.AddCartRequest;
import com.recruit.server.request.cart.ListCartRequest;
import com.recruit.server.request.cart.UpdateCartRequest;
import com.recruit.server.response.cart.AddCartResponse;
import com.recruit.server.response.cart.ListCartResponse;
import com.recruit.server.response.cart.UpdateCartResponse;
import com.recruit.server.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public ListCartResponse list(ListCartRequest request, HeaderInfo headerInfo) {
        ListCartResponse response = new ListCartResponse();
        try {
            if (headerInfo == null) {
                response.setCodeAndMessage(-1, "未登录，请先登录");
                return response;
            }

            // select carts from mysql db by userId
            List<Cart> cartList = cartMapper.selectCartByUserId(headerInfo.getUserId());
            if (!CollectionUtils.isEmpty(cartList)) {

                double totalPrice = 0.0;

                for (Cart cart : cartList) {
                    // select product from mysql db by productId
                    Product product = productMapper.selectByPrimaryKey(cart.getProductId());
                    ListCartResponse.CartItem cartItem = new ListCartResponse.CartItem();
                    cartItem.setCartId(cart.getId());
                    cartItem.setUserId(headerInfo.getUserId());
                    cartItem.setProductId(cart.getProductId());
                    cartItem.setQuantity(cart.getQuantity());
                    cartItem.setPrice(product.getPrice());
                    cartItem.setProductName(product.getName());
                    cartItem.setProductSubTitle(product.getSubtitle());
                    //计算金额
                    BigDecimal price = BigDecimalUtil.mul(product.getPrice().doubleValue(), cart.getQuantity());
                    cartItem.setCartPrice(price.doubleValue());
                    totalPrice = totalPrice + price.doubleValue();
                    response.getCartItems().add(cartItem);
                }
                response.setTotalPrice(totalPrice);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setCodeAndMessage(-1, "发生异常");
        }
        return response;
    }

    @Override
    public AddCartResponse add(AddCartRequest request, HeaderInfo headerInfo) {
        AddCartResponse response = new AddCartResponse();
        try {
            if (headerInfo == null) {
                response.setCodeAndMessage(-1, "未登录，请先登录");
                return response;
            }

            // select cart from mysql db by userId and productId
            Cart cart = cartMapper.selectCartByUserIdProductId(headerInfo.getUserId(), request.getProductId());
            if (cart == null) {
                // 如果购物车里没有这个商品，就新建条记录插入mysql数据库
                Cart cartItem = new Cart();
                cartItem.setQuantity(request.getCount());
                cartItem.setProductId(request.getProductId());
                cartItem.setUserId(headerInfo.getUserId());
                cartMapper.insert(cartItem);
            } else {
                // 如果购物车里有这个商品，就去更新下商品数量
                int count = cart.getQuantity() + request.getCount();
                cart.setQuantity(count);
                cartMapper.updateByPrimaryKeySelective(cart);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setCodeAndMessage(-1, e.getMessage());
        }
        return response;
    }

    @Override
    public UpdateCartResponse update(UpdateCartRequest request, HeaderInfo headerInfo) {
        UpdateCartResponse response = new UpdateCartResponse();
        try {
            if (headerInfo == null) {
                response.setCodeAndMessage(-1, "未登录，请先登录");
                return response;
            }

            // 查出购车记录，更新它的数量
            Cart cart = cartMapper.selectByPrimaryKey(request.getCartId());
            cart.setQuantity(request.getQuantity());
            cart.setUpdateTime(new Date());
            cartMapper.updateByPrimaryKey(cart);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setCodeAndMessage(-1, e.getMessage());
        }
        return response;
    }
}
